import { LogoutOutlined, SettingOutlined, RetweetOutlined } from '@ant-design/icons';
import { Menu, message, Spin } from 'antd';
import React from 'react';
import type { ConnectProps } from 'umi';
import { history, connect } from 'umi';
import type { ConnectState } from '@/models/connect';
import type { CurrentUser } from '@/models/user';
import HeaderDropdown from '../HeaderDropdown';
import Password from '../Password';
import ChangeCorp from '../ChanageCorp';
import styles from './index.less';
import { queryLogout } from '@/services/public';

export type GlobalHeaderRightProps = {
  currentUser?: CurrentUser;
  menu?: boolean;
} & Partial<ConnectProps>;

interface AvatarDropdownState {
  showpsw: boolean;
  showChange: boolean;
}

class AvatarDropdown extends React.Component<GlobalHeaderRightProps> {
  state: AvatarDropdownState = {
    showpsw: false,
    showChange: false,
  };

  render(): React.ReactNode {
    const {
      currentUser = {
        avatar: '',
        name: '',
        system: '',
        bankName: '',
        currentMobile: '',
        corps: [],
        selectCorpId: '',
      },
    } = this.props;
    const { showpsw, showChange } = this.state;

    const userCorps = currentUser.corps || [];

    const onMenuClick = async (event: {
      key: React.Key;
      keyPath: React.Key[];
      item: React.ReactInstance;
    }) => {
      const { key } = event;
      if (key === 'password') {
        this.setState({ showpsw: true });
        return;
      }
      if (key == 'corp') {
        this.setState({ showChange: true });
        return;
      }
      if (key === 'logout') {
        if (currentUser.system) {
          const res = await queryLogout({ type: currentUser.system });
          if (res && res.success) {
            const { dispatch } = this.props;
            if (dispatch) {
              dispatch({
                type: 'user/clearUser',
              });
              // dispatch({
              //   type: 'login/logout',
              // });
              if (window.location.hash.indexOf('/user/login') === -1 ) {
                history.replace({ pathname: '/user/login' })
              }
            }
            return;
          } else {
            message.error(res && res.errMsg || '无法退出');
          }
        } else {
          message.error('无法退出');
        }
      } else {
        history.push(`/account/${key}`);
      }
    };

    const menuHeaderDropdown = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
        {userCorps.length > 1 && (
          <Menu.Item key="corp">
            <RetweetOutlined />
            切换登录企业
          </Menu.Item>
        )}
        <Menu.Divider />
        <Menu.Item key="password">
          <SettingOutlined />
          修改登录密码
        </Menu.Item>
        <Menu.Divider />
        <Menu.Item key="logout">
          <LogoutOutlined />
          退出登录
        </Menu.Item>
      </Menu>
    );

    const cancel = () => {
      this.setState({ showpsw: false });
    };

    const corpChange = (value, corp) => {
      const { dispatch } = this.props;
      if (dispatch) {
        dispatch({
          type: 'user/setSelectCorp',
          payload: {
            selectCorpId: value,
            selectCorp: corp,
          },
        });
      }
      this.setState({ showChange: false });
      history.push('/construction/manage')
      window.location.reload();
    };

    return currentUser && currentUser.name ? (
      <span>
        <HeaderDropdown overlay={menuHeaderDropdown}>
          <span className={`${styles.action} ${styles.account}`}>
            {currentUser && currentUser.bankName ? (
              <span style={{ fontSize: '12px' }}>{currentUser.bankName}</span>
            ) : null}
            <span className={styles.avatarName}>{currentUser.name}</span>
          </span>
        </HeaderDropdown>
        {showpsw && currentUser.system && currentUser.currentMobile && (
          <Password
            modalVisible={showpsw}
            system={currentUser.system}
            mobile={currentUser.currentMobile}
            onCancel={cancel}
          />
        )}
        {showChange && (
          <ChangeCorp
            showCancel={true}
            modalVisible={showChange}
            cardList={userCorps}
            select={currentUser.selectCorpId}
            onOk={(value, corp) => {
              corpChange(value, corp);
            }}
            onCancel={() => {
              this.setState({ showChange: false });
            }}
          />
        )}
      </span>
    ) : (
      <span className={`${styles.action} ${styles.account}`}>
        <Spin
          size="small"
          style={{
            marginLeft: 8,
            marginRight: 8,
          }}
        />
      </span>
    );
  }
}

export default connect(({ user }: ConnectState) => ({
  currentUser: user.currentUser,
}))(AvatarDropdown);
